<template>
  <div class="container">
    <div class="container-top">
      <div class="title">
        <h3>叩丁狼电商运营平台</h3>
        <div class="icon" @click="isCollapse = !isCollapse">
          <el-icon>
            <IconMenu />
          </el-icon>
        </div>

      </div>
      <div class="admin">
        <el-dropdown @command="onCommand">
          <span class="el-dropdown-link">
            {{username}}
            <el-icon>
              <ArrowDown />
            </el-icon>
          </span>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="home">首页</el-dropdown-item>
              <el-dropdown-item command="logout">退出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

      </div>

    </div>
    <div class="container-bottom">
      <div class="menus-container">
        <el-menu :default-active="defaultActive" class="el-menu-vertical-demo" text-color="#fff" active-color="#409eff"
          background-color="rgb(48, 65, 86)" :collapse="isCollapse" :unique-opened="true" :router="true">
          <el-menu-item index="/index">
            <i class="iconfont homepage"></i>

            <template #title>
              <span>首页</span>
            </template>
          </el-menu-item>

          <el-sub-menu :index="item.id.toString()" v-for="(item,index) in sortedMenu" :key="item.id">
            <template #title>
              <i :class="['iconfont',item.icon]"></i>
              <span>{{item.title}}</span>
            </template>

            <el-menu-item :index="'/'+item.name+'/'+el.name" v-for="el in item.children" :key="item.id">
              <template #title>
                <i :class="['iconfont',el.icon]"></i>
                <span>{{el.title}}</span>
              </template>

            </el-menu-item>
          </el-sub-menu>

        </el-menu>
      </div>
      <div class="content-container">
        <div class="myBreadCrumb">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(item,index) in crumbList" :to="{path:'/'+item.name}">{{item.title}}
            </el-breadcrumb-item>
            <!-- <a :href=></a> -->
          </el-breadcrumb>
        </div>
        <RouterView />
      </div>
    </div>
  </div>
</template>



<script setup lang="ts">
import * as api from "@/request/api"
import { useUserInfoStore } from "@/stores/userInfo";
import { Menu as IconMenu, ArrowDown } from "@element-plus/icons-vue";
import { computed } from "@vue/reactivity";
import Cookies from "js-cookie";
import { nextTick, ref, watch, type Ref } from "vue";
import { RouterView, useRoute, useRouter } from 'vue-router'


//  Menu as IconMenu 组件别名
// 【】获取仓库实例
const userInfoStore = useUserInfoStore();
// 【】获取路由实例
const router = useRouter();
const route = useRoute();
// 【】是否折叠
let isCollapse = ref(false);


// 【】面包屑
interface ICrumbList {
  name?: string;
  title?: string;
}
let crumbList: Ref<ICrumbList[]> = ref([]);
const getCrumbList = () => {
  if (crumbList.value) {
    // 重新跳转时清除上一次的面包屑
    crumbList.value = [];
  }
  // 分割当前 路由，得到数组如['','ums','admin']
  let pathArr = route.path.split("/");

  // 数组第二项为index，则不继续渲染面包屑
  if (pathArr[1] === "index") {
    crumbList.value = [];
  } else {
    // 数组第二项为其他，则根据排序好的菜单筛选面包屑的每一项。
    // await nextTick();
    let menuItem = userInfoStore.sortedMenu.find(item => item.name === pathArr[1]);
    // 添加二级目录
    crumbList.value.push({
      title: menuItem?.title,
      name: menuItem?.name
    });
    let subItem = menuItem?.children?.find(item => item.name === pathArr[2]);
    // 添加三级目录
    crumbList.value.push({
      title: subItem?.title,
      name: subItem?.name
    });
  }
}



// 【】获取当前路由，确定激活的菜单项
// 默认active，需要跟随路由而改变
let defaultActive = ref('/index');
// 监听路由
watch(useRoute(), //相当于vue2的this.$route
  (newVal) => {
    // console.log(newVal);
    defaultActive.value = newVal.path;
    getCrumbList();//获取面包屑
  }, {
  immediate: true,//开启立即监听，刷新也能检测到
})


// 【】获取用户信息
let username = ref("");
username.value = userInfoStore.username;


// 【】从仓库获取渲染菜单的数据
// const sortedMenu = ref();
// sortedMenu.value = userInfoStore.menus;

// setTimeout(() => {
//   userInfoStore.menus = [];
// }, 5000);

// 写成计算属性获取仓库的getters，这样才能实现响应式（仓库清空，页面也清空）
const sortedMenu = computed(() => {
  // console.log(userInfoStore.sortedMenu);
  return userInfoStore.sortedMenu
})



// 【】下拉框路由跳转
// 无法在事件里获取useRoute
const onCommand = async (command: string) => {
  if (command === "home") {
    router.push("/index");
  }
  else if (command === "logout") {
    let result = await api.admin.logout();
    console.log(result);

    Cookies.remove("token");
    useUserInfoStore().updateUserInfo([], '', []);
    router.push("/login");
  }
}

// 面包屑
// console.log(defaultActive);
// console.log(sortedMenu);
// sms : title2
// pms : title2
// const onSelect = (index, indexPath, item, routeResult) => {
//   console.log(index, indexPath, item, routeResult);
// }








</script>


<style scoped lang="scss">
.container {
  width: 100%;
  height: 100vh;
  display: flex; //top + bottom 保证高度100vh
  flex-direction: column;
  overflow: hidden; //隐藏外侧滚动条
}

.container-top {
  height: 70px;
  background-color: #409eff;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;

  .title {
    display: flex;
    line-height: 70px;
    color: #fff;

    h3 {
      font-size: 24px;
    }

    .icon {
      display: flex;
      font-size: 20px;
      align-items: center;
      padding: 0 20px;
    }
  }

  .admin {
    display: flex;
    align-items: center;
    line-height: 70px;

    .el-dropdown {
      color: #fff;
    }
  }

}

.container-bottom {
  flex: 1;
  display: flex;
  overflow: hidden; //隐藏中间盒子滚动条

  .menus-container {
    background-color: rgb(48, 65, 86);
    // width: 250px;
    color: #fff;
    height: 100%; //限制高度
    overflow-y: auto; //显示里侧滚动条
    text-align: center;



    &::-webkit-scrollbar {
      width: 0; //滚动条宽度为0
    }





    // 侧边菜单样式
    :deep(.el-menu) {
      border: none;

      .el-sub-menu__title:hover {
        background-color: rgb(38, 52, 69) !important; //原来是行内样式
      }

    }
  }

  .content-container {
    position: relative;
    // background-color: #cfc;
    flex: 1;
    // text-align: center;//影响行内样式
    height: 100%;
    overflow-y: auto;

    .myBreadCrumb {
      padding: 15px 20px;
      border-bottom: 1px solid #eee;
      position: fixed;
      background: #fff;
      z-index: 100;
      width: 100%;
    }
  }
}

// .el-aside {
//   transition: width 0.15s !important;
// }
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 250px;
}
</style>
